package interpreter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.util.ArrayList;

public class InterpreterMain {
	// SKIP a reading in the beginning & a reading in the end
	// For example if Config.interpreter_step == 30 * 1000 &
	//    & if the SKIP_MARGINS = 2 ====> skipping 1 minute at the beginning
	//										& 1 minute at the end
	//										to remove warmup & cooldown
	// TODO: CHANGE THIS TO AT LEAST 2
	// TODO: Is it done yet?
	public static int SKIP_MARGINS = 2;
	
	public static void main(String []args) {
		if(args.length < 1) {
			System.out.println("Please use arguments:");
			System.out.println("<arg1>: folder with .raw experiment files");
			
			return ;
		}
		
		new InterpreterMain(args);
	}

	private ArrayList<RealResult> realResults;
	private String gnuplotScriptSingleExperiment = "";
	private String gnuplotScriptOneParameterVariation = "";
	private String gnuplotScriptTwoParameterVariation = "";
	
	public void InterpretFolder(String folder) {
		// Go trough all the .raw files
		File dir = new File(folder);
	    
	    FilenameFilter filter = new FilenameFilter() {
	        public boolean accept(File dir, String name) {
	            return name.endsWith(".raw");
	        }
	    };
	    String []children = dir.list(filter);
	    String []folder_parts = folder.split("_");
	    int MM = Integer.parseInt(folder_parts[0].substring(0, folder_parts[0].length()-1));
	    int SS = Integer.parseInt(folder_parts[1].substring(0, folder_parts[1].length()-1));
	    int CC = Integer.parseInt(folder_parts[2].substring(0, folder_parts[1].length()-1));
	    
	    this.gnuplotScriptSingleExperiment = "";
	    if (children == null) {
	        // Either dir does not exist or is not a directory
	    } else {
	        for (int i=0; i<children.length; i++) {
	            // Get filename of file or directory
	            String filename = children[i];
	            String in = filename;
	            String out = filename.replaceAll("\\.raw", ".txt");
	            
	            String inpath = folder + (folder.endsWith("/") ? in : "/" + in);
	            String outpath = folder + (folder.endsWith("/") ? out : "/" + out);
	            
	            String []parts = (filename.replaceAll("\\.raw", "")).split("_");
	            int C = Integer.parseInt(parts[0].substring(1));
	            int P = Integer.parseInt(parts[1].substring(1));
	            int L = Integer.parseInt(parts[2].substring(1));
	            int M = Integer.parseInt(parts[3].substring(1));
	            
	            if ( M % P !=0 ) {
	            	System.err.println("Bad experiment file, M % P != 0 for " + filename);
	            	return;
	            }
	            
	            if ( P != SS) {
	            	System.err.println("Bad experiment file, P != SS for " + filename);
	            	return;
	            }
	            
	            M = M / P;
	            P = 1;
	            
	            int []params = new int[] { 
	            		MM, 
	            		SS,
	            		CC,
	            		C, 
//	            		P, 
//	            		L, 
	            		M 
	            }; 
	            
	            RealResult r = SingleExperimentInterpreter.DoFile(params,inpath,outpath);
	            realResults.add(r);
	            
	            this.gnuplotScriptSingleExperiment += SingleExperimentInterpreter.getGnuPlotForExperiment(out, params);
	        }
	    }
	    
	    String outFilename;
	    
	    outFilename = folder + (folder.endsWith("/") ? "single.p" : "/single.p");
	    writeStringToFile(outFilename, this.gnuplotScriptSingleExperiment);
	}
	
	public InterpreterMain(String[] folders) {
		
		realResults = new ArrayList<RealResult>();
		
	    RealResult.params_codes = new String [] { 
	    	"MM",
	    	"SS",
	    	"CC",
	    	"C",
//	    	"P",
//	    	"L",
	    	"M" };
	    RealResult.params_names = new String [] {
    		"Number of Middle Men",
			"Number of Servers",
			"Number of Cores",
			"Number of Clients",
//			"Number of Queues",
//			"Size of Queues",
			"Number of Worker Threads" };

	    for(String folder : folders) {
			InterpretFolder(folder);
		}
		
	    System.err.println("Collecting data from " + realResults.size() + " experiments.");
	    
	    String outFilename;
	    
	    for(RealResult r : realResults) {
	    	// Try to make some params variable
	    	int []params;
	    	for(int i=0; i<r.params.length; i++) {
	    		params = r.params.clone();
	    		params[i] = 0;
	    		gnuplotScriptOneParameterVariation += OneParameterVariation.doFilesAndPlot("gnuplot", i, params, realResults);
	    	}
	    	for(int i=0; i<r.params.length; i++) {
	    		for(int j=0; j<r.params.length; j++) {
	    			params = r.params.clone();
	    			params[i] = 0;
	    			params[j] = 0;
	    			gnuplotScriptTwoParameterVariation += TwoParameterVariation.plotVeryInterestingResults("gnuplot", params, i, j, realResults);
	    		}
	    	}
	    }
	    
	    outFilename = "gnuplot/one.p";
	    writeStringToFile(outFilename, this.gnuplotScriptOneParameterVariation);

	    outFilename = "gnuplot/two.p";
	    writeStringToFile(outFilename, this.gnuplotScriptTwoParameterVariation);

	    
	}
	
	private static void writeStringToFile(String filename, String contents) {
		try {
	    	FileWriter fstream = new FileWriter(filename, false);
			BufferedWriter outFile = new BufferedWriter(fstream);
			outFile.write(contents);
			outFile.close();
		} catch (Exception e) {
			System.out.println("Can't write to "+filename+"!!!");
			e.printStackTrace();
		}
	}
	
	
	
	
	
	

}
